const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const axios = require('axios');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

// DeepSeek API 配置
const DEEPSEEK_API_URL = 'https://api.deepseek.com/chat/completions'; // 假设的 API 地址
const DEEPSEEK_API_KEY = 'sk-14d961726010417e99250d3b8a4b42f3'; // 替换为你的 DeepSeek API 密钥

// 静态文件服务（用于前端页面）
app.use(express.static('public'));

// Socket.io 连接处理
io.on('connection', (socket) => {
    console.log('a user connected');

    // 监听客户端发送的消息
    socket.on('chat message', async (msg) => {
        console.log('message: ' + msg);

        // 调用 DeepSeek API 获取回复
        try {
            const response = await axios.post(
                DEEPSEEK_API_URL,
                {
                    message: msg, // 发送的消息内容
                },
                {
                    headers: {
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
                        'Content-Type': 'application/json',
                    },
                }
            );

            // 将 DeepSeek 的回复发送回客户端
            const reply = response.data.reply; // 假设 API 返回的回复字段是 reply
            io.emit('chat message', reply);
        } catch (error) {
            console.error('Error calling DeepSeek API:', error);
            io.emit('chat message', 'Sorry, something went wrong.');
        }
    });

    // 用户断开连接
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
});

// 启动服务器
server.listen(3000, () => {
    console.log('listening on *:3000');
});